package cn.itcast.hotel.service.impl;

import cn.itcast.hotel.mapper.HotelMapper;
import cn.itcast.hotel.pojo.Hotel;
import cn.itcast.hotel.pojo.HotelDoc;
import cn.itcast.hotel.pojo.PageResult;
import cn.itcast.hotel.pojo.RequestParams;
import cn.itcast.hotel.service.IHotelService;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.elasticsearch.action.delete.DeleteRequest;
import org.elasticsearch.action.delete.DeleteResponse;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.geo.GeoPoint;
import org.elasticsearch.common.unit.DistanceUnit;
import org.elasticsearch.common.xcontent.XContentType;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.index.query.functionscore.FunctionScoreQueryBuilder;
import org.elasticsearch.index.query.functionscore.ScoreFunctionBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.aggregations.AggregationBuilders;
import org.elasticsearch.search.aggregations.Aggregations;
import org.elasticsearch.search.aggregations.bucket.terms.Terms;
import org.elasticsearch.search.sort.SortBuilders;
import org.elasticsearch.search.sort.SortOrder;
import org.elasticsearch.search.suggest.Suggest;
import org.elasticsearch.search.suggest.SuggestBuilder;
import org.elasticsearch.search.suggest.SuggestBuilders;
import org.elasticsearch.search.suggest.completion.CompletionSuggester;
import org.elasticsearch.search.suggest.completion.CompletionSuggestion;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
@Slf4j
public class HotelService extends ServiceImpl<HotelMapper, Hotel> implements IHotelService {
    @Autowired
    RestHighLevelClient client;

    @Autowired
    IHotelService iHotelService;


    @Override
    public PageResult search(RequestParams params) {
        try {
            SearchRequest request = new SearchRequest("hotel");
            //直接调用方法
            buildBasicQuery(params,request);

           SearchResponse response = client.search(request,RequestOptions.DEFAULT);
           return handleResponse(response);

        } catch (IOException e) {
            e.printStackTrace();
            //出现异常打印出来
            log.error("执行搜索功能出现异常，异常的原因是{}",e.getMessage());
        }
        return null;
    }


    //聚合搜索条件
    @Override
    public Map<String, List<String>> filters(RequestParams params) {
        //创建搜索对象

        SearchRequest request = new SearchRequest("hotel");
        //搜索条件的设置 ，这里服用search方法的搜索条件
        buildBasicQuery(params,request);

        //设置聚合处理，按照品牌，星际，城市分桶
        request.source().size(0);
        request.source().aggregation(
                AggregationBuilders.terms("brandAgg").field("brand").size(20));
        request.source().aggregation(
                AggregationBuilders.terms("starAgg").field("starName").size(20));
        request.source().aggregation(
                AggregationBuilders.terms("cityAgg").field("city").size(20));
        //执行搜索
        try {
            SearchResponse response = client.search(request, RequestOptions.DEFAULT);
            //解析响应结果
            Aggregations aggregations = response.getAggregations();

            List<String> brandAgg = getAggByname(aggregations, "brandAgg");
            List<String> starAgg = getAggByname(aggregations, "starAgg");
            List<String> cityAgg = getAggByname(aggregations, "cityAgg");

            //封装
            Map<String , List<String>> result = new HashMap<>();
            result.put("brand",brandAgg);
            result.put("starName",starAgg);
            result.put("city",cityAgg);
            return result;
        } catch (IOException e) {
            e.printStackTrace();
            throw  new RuntimeException("聚合获取条件失败");
        }
    }


    //拼音加补全
    @Override
    public List<String> getsuggestion(String key) {
        try {
            SearchRequest request = new SearchRequest("hotel");

            request.source().suggest(new SuggestBuilder().addSuggestion("mySuggestion"
                    , SuggestBuilders.completionSuggestion("suggestion")
                                     .prefix(key)
                                      .skipDuplicates(true)
                                        .size(10)
            ));
            SearchResponse response = client.search(request, RequestOptions.DEFAULT);

            Suggest suggest = response.getSuggest();
            CompletionSuggestion suggestion = suggest.getSuggestion("mySuggestion");

            List<CompletionSuggestion.Entry.Option> options = suggestion.getOptions();
            List<String> list = new ArrayList<>();
            for (CompletionSuggestion.Entry.Option option : options) {
               list.add(option.getText().toString()) ;
            }
            return list;
        } catch (IOException e) {
            e.printStackTrace();
            throw new RuntimeException(e);
        }
    }

    //数据同步
    @Override
    public void insert(Long hotelId) {
        try {
        Hotel hotel = iHotelService.getById(hotelId);
        HotelDoc hotelDoc = new HotelDoc(hotel);

        IndexRequest request = new IndexRequest("hotel");

        request.id(String.valueOf(hotelDoc.getId()));
        request.source(JSON.toJSONString(hotelDoc), XContentType.JSON);

           client.index(request, RequestOptions.DEFAULT);
        } catch (IOException e) {
            e.printStackTrace();
            log.error("删除文档失败 ，文档id{}  失败原因{}",hotelId,e.getMessage());
        }
    }

    @Override
    public void delete(Long hotelId) {
        try {
        DeleteRequest request = new DeleteRequest("hotel",String.valueOf(hotelId));
            DeleteResponse delete = client.delete(request, RequestOptions.DEFAULT);
        } catch (IOException e) {
            e.printStackTrace();
            log.error("删除文档失败 ，文档id{}  失败原因{}",hotelId,e.getMessage());
        }
    }


    //解析aggs的方法抽取
     public List<String> getAggByname( Aggregations aggregations,String name){
         Terms brandAgg = aggregations.get(name);
         List<String> list = new ArrayList<>();
         List<? extends Terms.Bucket> buckets = brandAgg.getBuckets();
         for (Terms.Bucket bucket : buckets) {
             list.add(bucket.getKeyAsString());
         }
         return list;
     }

    //基础构建查询
    public void buildBasicQuery(RequestParams params, SearchRequest request){

        BoolQueryBuilder boolQuery = QueryBuilders.boolQuery();

        String key = params.getKey();
        //key不为空
        if (StringUtils.isNoneBlank(key)) {
           boolQuery.must(QueryBuilders.matchQuery("all",key));
        }
      //判断城市
        if (StringUtils.isNotBlank(params.getCity())) {
            boolQuery.filter(QueryBuilders.termQuery("city",params.getCity()));
        }
        //term查询品牌
        if (StringUtils.isNotBlank(params.getBrand())) {
            boolQuery.filter(QueryBuilders.termQuery("brand",params.getBrand()));
        }
        //term查询星级
        if (StringUtils.isNotBlank(params.getStarName())) {
            boolQuery.filter(QueryBuilders.termQuery("starName",params.getStarName()));
        }
        if (params.getMinPrince()!=null && params.getMaxPrince()!=null){
            boolQuery.filter(QueryBuilders.rangeQuery("price")
                    .gte(params.getMinPrince()).lte(params.getMaxPrince()));
        }

        //设置分页
        Integer page = params.getPage();
        Integer pageSize = params.getSize();
        request.source().from((page-1)*pageSize).size(pageSize);


        //查询位置
        if (StringUtils.isNotBlank(params.getLocation())) {
            request.source().
                    sort(SortBuilders.geoDistanceSort("location"
                    ,new GeoPoint(params.getLocation()))
                    .order(SortOrder.ASC)
                    .unit(DistanceUnit.KILOMETERS)
                    );
        }


        FunctionScoreQueryBuilder functionScoreQueryBuilder = QueryBuilders.functionScoreQuery(
                boolQuery,
                new FunctionScoreQueryBuilder.FilterFunctionBuilder[]{
                        new FunctionScoreQueryBuilder.FilterFunctionBuilder(
                                QueryBuilders.termQuery("isAD",true),
                                ScoreFunctionBuilders.weightFactorFunction(3)
                        )
                }
        );
        request.source().query(functionScoreQueryBuilder);






    }



    //出街结果的方法
    public PageResult handleResponse(SearchResponse response){
        //处理返回响应
        SearchHits hits = response.getHits();
        //得到总数total
        long total = hits.getTotalHits().value;
        SearchHit[] docAll = hits.getHits();
        //创建HotelDoc的集合
        List<HotelDoc> list = new ArrayList<>();
        for (SearchHit doc : docAll) {
            String jsonStr = doc.getSourceAsString();
            HotelDoc hotelDoc = JSON.parseObject(jsonStr, HotelDoc.class);
            Object[] sortValues = doc.getSortValues();
            if (sortValues.length>0){
                Object sortValue = sortValues[0];
                hotelDoc.setDistance(sortValue);
            }
            list.add(hotelDoc);
        }
       return new PageResult(total,list);
    }
}
